package com.hkts.beltweigher.websocket.sendUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hkts.beltweigher.websocket.MessageConstants;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class NettySendUtil {

    private static int heartbeatCount = 0;
    public static void sendPongMsg(ChannelHandlerContext context) {
        context.channel().writeAndFlush(new TextWebSocketFrame(MessageConstants.PONG_MSG));
        heartbeatCount++;
//        System.out.println( " sent pong msg to " + context.channel().remoteAddress() + ", count: " + heartbeatCount);
    }

    public static void sendAllMessage(ResultMsg resultMsg, ChannelGroup channelGroup){
        String message= JSONArray.toJSON(resultMsg).toString();
        //log.info("netty sendAllMessage to msg {}",message);
        channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }
    public static void sendPointMessage(ResultMsg resultMsg, ChannelHandlerContext ctx){
        String message= JSON.toJSONStringWithDateFormat(resultMsg,"yyyy-MM-dd HH:mm:ss");
//        String message= JSONArray.toJSON(resultMsg).toString();
        log.info("netty sendPointMessage to msg {}",message);
        //收到信息后，根据id发送消息
        ctx.writeAndFlush(new TextWebSocketFrame(message));
    }
    /*
     *
     * */
    public static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            if(arr.length>=2){

                for (String s : arr){
                    String key = s.split("=")[0];
                    String value = s.split("=")[1];
                    map.put(key,value);
                }
            }
            return  map;

        }else{
            return map;
        }
    }

}
